import 'dart:convert';

import 'package:enterprise_v6_app/app/components/dialog/multiple_bottom_sheet/custom_multiple_bottom_sheet.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/common/simple_choice_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/application/smart_warehouse/warehouse_device_static_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/smart_warehouse/warehouse_device_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/smart_warehouse/warehouse_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/smart_warehouse/smart_warehouse_controller.dart';
import 'package:enterprise_v6_app/app/modules/profile/controller.dart';
import 'package:get/get.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class DeviceMangerController extends GetxController {
  // 设备列表
  final deviceList = <WarehouseDeviceStaticEntity>[];
  Future<List<WarehouseDeviceStaticEntity>> getList() async {
    final params = <String, dynamic>{};
    if (warehouse != null) {
      params['warehouseId'] = warehouse?.id;
    }
    final resp = await HttpUtil()
        .generateGetRequest<List<WarehouseDeviceStaticEntity>>(
          '${Interface.mainBaseUrl}/storage//storageStatistics/getWarehouseStatic',
          queryParameters: params,
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        deviceList.clear();
        deviceList.addAll(result.data!);
        update();
      }
    });
    return resp.data ?? [];
  }

  // 监控类 仪表类
  List<SimpleChoiceBean> inventoryList = [];
  // 选中的类型
  SimpleChoiceBean? selectInventory;
  Future<void> getDevType() async {
    final resp = await HttpUtil()
        .generateGetRequest<List<WarehouseDeviceTreeEntity>>(
          '${Interface.mainBaseUrl}/storage//device/getDeviceTree',
        )
        .execute();
    if (resp.data != null) {
      inventoryList.clear();
      for (final item in resp.data!) {
        if (item.name != '监控类' && item.name != '仪表类') continue;
        inventoryList.add(SimpleChoiceBean(id: item.id, name: item.name ?? '未知'));
      }
      update();
    }
  }

  void showInventorySelection() {
    CustomEquipmentBottomSheet<SimpleChoiceBean>(
      dataList: inventoryList,
      checkedList: selectInventory == null ? [] : [selectInventory!],
      onConfirm: (value) {
        selectInventory = value.firstOrNull;
        refreshPage();
        update();
      },
      title: '选择类型',
      isMultiple: false,
    ).showBottomSheetDialog();
  }

  /// 当前选择仓库
  WarehouseEntity? warehouse;
  void showWarehouseSelection() {
    // 获取仓库列表
    final warehouseList = Get.find<SmartWarehouseController>().warehouseList;
    CustomSelectFunction.selectMultipleBottomSheet<WarehouseEntity>(
      title: '所在仓库',
      dataList: warehouseList,
      checkedList: warehouse == null ? [] : [warehouse!],
      isMultiple: false,
      onCallBack: (value) {
        warehouse = value.firstOrNull;
        refreshPage();
        update();
      },
    );
  }

  /// 搜索刷新页面
  void refreshPage() {
    getList();
  }

  WebSocketChannel? channel;

  /// raw:
  /// ```json
  /// {"data":{
  ///   "humidity":63.0,
  ///   "id":"6fe8c582-9078-4622-9dde-8ff994e48071",
  ///   "relay":0,
  ///   "temperature":6.5
  /// },"type":2}
  /// ```
  Future<void> connectWS() async {
    final ctrl = Get.find<HomeMyController>();
    final companyCode = ctrl.entity?.companyCode;
    if (companyCode == null) {
      AppToast.showError('获取企业信息失败!');
      return;
    }
    final wsUrl = Uri.parse(Interface.getWarehouseWebSocket(companyCode));
    channel = WebSocketChannel.connect(wsUrl);

    channel?.stream.listen((message) {
      try {
        final data = json.decode(message as String);
        if (data['type'] != 2) return;
        final entity = deviceList.firstWhereOrNull((element) => element.id == data['data']['id']);
        if (entity == null) return;
        entity.temperature = data['data']['temperature'] as double;
        entity.humidity = data['data']['humidity'] as double;
        update();
      } catch (_) {}
    });
  }

  @override
  void onInit() {
    super.onInit();
    getDevType();
    getList();
    connectWS();
  }

  @override
  void onClose() {
    super.onClose();
    channel?.sink.close();
  }
}
